<?php

namespace app\service\alone\Tools;

use app\service\alone\BaseService;
use Curl\Curl;

class CurlService extends BaseService
{
    /** @var Curl $client */
    private $client;

    protected function init()
    {
        $this->client = new Curl();
    }

    /**
     * 获取客户端
     *
     * @param bool $isSSL 是否需 SSL 验证
     * @return Curl
     */
    public function client(bool $isSSL = false): Curl
    {
        $this->client->reset();

        if (!$isSSL) {
            $this->client->setOpt(CURLOPT_SSL_VERIFYHOST, false);
            $this->client->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        }

        return $this->client;
    }

    /**
     * 处理返回数据
     *
     * @param array $request ["url" => "请求地址", "body" => "请求数据"]
     * @param Curl $curl
     * @param bool $isResponseJson 返回结果是否需 json_decode
     * @return array
     */
    public function returnData(array $request, Curl $curl, bool $isResponseJson = true): array
    {
        // 初始化变量
        $info = [
            'request' => [
                'url' => $request['url'],
                'header' => json_encode($curl->request_headers),
                'body' => json_encode($request['data']),
            ],

            'response' => [
                'header' => json_encode($curl->response_headers),
                'body' => $curl->getResponse()
            ]
        ];

        // 判断 http 请求是否失败
        if ($curl->error) return echoArr(500, $curl->getErrorMessage(), ['package' => $info]);

        return echoArr(200, '请求成功', [
            'result' => $isResponseJson ? json_decode($info['response']['body'], true) : $info['response']['body'],

            'package' => $info
        ]);
    }
}